package com.Sdebruijn.curriculumvitae.util;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.Sdebruijn.curriculumvitae.R;
import com.Sdebruijn.curriculumvitae.models.Applicant;
import com.Sdebruijn.curriculumvitae.models.Person;

/**
 * Utility class containing multiple helping methods used when the user clicks
 * on some shown data which is linked to an action
 * 
 * @author Stefan de Bruijn
 * 
 */
public class OnClickUtils {

	/**
	 * The official LinkedIn app its package name. Used to check if the user has
	 * this app installed.
	 */
	private static final String LINKEDIN_PACKAGE = "com.linkedin.android";

	/**
	 * Open any Mail app with prefilled data
	 * 
	 * @param context
	 *            Activity context
	 * @param email
	 *            Email address to pre-fill
	 */
	public static void sendMail(final Context context, final String email) {
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { email });
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Reply to CV app");

		context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	}

	/**
	 * Calls the given phone number
	 * 
	 * @param context
	 *            Activity context
	 * @param number
	 *            Phone number to call
	 */
	public static void startPhoneCall(final Context context, final String number) {

		Intent callIntent = new Intent(android.content.Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:" + number));
		context.startActivity(callIntent);
	}

	/**
	 * Adds a person as contact <br />
	 * Shows a pop up to confirm the data and give a choice whether to add
	 * automatically or manually.
	 * 
	 * @param context
	 *            Activity context
	 * @param person
	 *            {@link Person} Person to add to the contacts list
	 */
	public static void addAsContact(final Context context, final Applicant applicant) {

		final Dialog dialog = new Dialog(context);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_contact_confirm);

		// Find and update the data fields
		final TextView email = (TextView) dialog.findViewById(R.id.tv_email);
		email.setText(applicant.email);

		final TextView mobile = (TextView) dialog.findViewById(R.id.tv_mobile);
		mobile.setText(applicant.mobile);

		final TextView name = (TextView) dialog.findViewById(R.id.tv_name);
		name.setText(applicant.name);

		Button button_confirmed = (Button) dialog
				.findViewById(R.id.btn_dialog_add_contact_confirmed);
		button_confirmed.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				addAsContactConfirmed(context, applicant);
			}
		});

		Button button_automatic = (Button) dialog
				.findViewById(R.id.btn_dialog_add_contact_automatic);
		button_automatic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				addAsContactAutomatic(context, applicant);
			}
		});

		dialog.show();

	}

	/**
	 * Open the add-contact screen with pre-filled info
	 * 
	 * @param context
	 *            Activity context
	 * @param person
	 *            {@link Person} to add to contacts list
	 */
	public static void addAsContactConfirmed(final Context context, final Person person) {

		Intent intent = new Intent(Intent.ACTION_INSERT);
		intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

		intent.putExtra(ContactsContract.Intents.Insert.NAME, person.name);
		intent.putExtra(ContactsContract.Intents.Insert.PHONE, person.mobile);
		intent.putExtra(ContactsContract.Intents.Insert.EMAIL, person.email);

		context.startActivity(intent);

	}

	/**
	 * Automatically add a contact into someone's contacts list
	 * 
	 * @param context
	 *            Activity context
	 * @param person
	 *            {@link Person} to add to contacts list
	 */
	public static void addAsContactAutomatic(final Context context, final Person person) {
		String displayName = person.name;
		String mobileNumber = person.mobile;
		String email = person.email;

		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

		ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
				.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
				.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

		// Names
		if (displayName != null) {
			ops.add(ContentProviderOperation
					.newInsert(ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
					.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
							displayName).build());
		}

		// Mobile Number
		if (mobileNumber != null) {
			ops.add(ContentProviderOperation
					.newInsert(ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
					.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobileNumber)
					.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
							ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
		}

		// Email
		if (email != null) {
			ops.add(ContentProviderOperation
					.newInsert(ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
					.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
					.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
							ContactsContract.CommonDataKinds.Email.TYPE_WORK).build());
		}

		// Asking the Contact provider to create a new contact
		try {
			context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Toast.makeText(context, "Contact " + displayName + " is toegevoegd.", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * Show the activity picker for Google+. Will give the user the option to
	 * open with browser or Google+ app when installed
	 * 
	 * @param context
	 *            Activity context
	 * @param id
	 *            Google+ account id
	 */
	public static void openGooglePlusProfile(final Context context, final String id) {
		context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://plus.google.com/"
				+ id + "/posts")));
	}

	/**
	 * Open someone's LinkedIn profile. If the LinkedIn app is installed it will
	 * open the app, if not it will open the mobile web version with the
	 * browser.
	 * 
	 * @param context
	 *            Activity context
	 * @param id
	 *            LinkedIn account id
	 */
	public static void openLinkedinProfile(final Context context, final String id) {
		if (isAppInstalled(context, LINKEDIN_PACKAGE)) {

			Intent linkedinIntent = new Intent(Intent.ACTION_VIEW);
			linkedinIntent.setClassName(LINKEDIN_PACKAGE,
					"com.linkedin.android.profile.ViewProfileActivity");
			linkedinIntent.putExtra("memberId", id);
			context.startActivity(linkedinIntent);

		} else {
			openBrowser(context, "http://www.linkedin.com/profile/view?id=" + id);
		}

	}

	/**
	 * Opens the browser with the given link
	 * 
	 * @param context
	 *            Activity context
	 * @param url
	 *            String url to open
	 */
	public static void openBrowser(Context context, String url) {
		if (url != null && url.length() > 0) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			context.startActivity(browserIntent);
		}
	}

	/**
	 * Check if an app is installed by its packageName
	 * 
	 * @param context
	 *            Activity context
	 * @param packageName
	 *            PackageName of the app
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		boolean installed = false;
		try {
			pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
			installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			installed = false;
		}
		return installed;
	}

	/**
	 * Opens Google its Play Store on the given app
	 * 
	 * @param context
	 *            Activity context
	 * @param packageName
	 *            PackageName of the app
	 */
	public static void openPlayStore(final Context context, String packageName) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse("market://details?id=" + packageName));
		context.startActivity(intent);
	}

}
